package com.aiti.lulian.controller;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.base.core.utils.stringUtil.StringUtil;
import com.aiti.lulian.constant.NotificationConstant;
import com.aiti.lulian.entity.CorporateStrengthPic;
import com.aiti.lulian.entity.LuLianSupplierSignUp;
import com.aiti.lulian.entity.ShowSupplierSignUpFile;
import com.aiti.lulian.service.*;
import com.aiti.lulian.utils.NotificationUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/supplierSignUp")
public class LuLianSupplierSignUpController extends WebController {
    @Resource
    private ILuLianSupplierSignUpService supplierSignUpService;
    @Resource
    private ILulianEnterpriseHistoryService enterpriseHistoryService;
    @Resource
    private IShowSupplierSignUpFileService showSupplierSignUpFileService;
    @Resource
    private ILuLianSupplierInquiryOrderService supplierInquiryOrderService;
    @Autowired
    private ISignUpMessageService signUpMessageService;
    @Autowired
    private NotificationUtils notificationUtils;
    @Autowired
    private ICorporateStrengthPicService corporateStrengthPicService;

    /**
     * 新增
     *
     * @param supplierSignUp 新增数据
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/6/14
     * @author yangfenzhen
     */
    @PostMapping
    public Message supplierSignUp(@RequestBody LuLianSupplierSignUp supplierSignUp) {
        String userId = findUserId();
        if (StringUtil.isBlank(userId)) {
            userId = supplierSignUp.getUserId();
            if (StringUtil.isBlank(userId)) {
                return Message.fail("请登陆");
            }
        }

//        if(StringUtil.isBlank(supplierSignUp.getBuyerCompanyId()) || StringUtil.isBlank(supplierSignUp.getSellerCompanyId())){
//            return Message.fail("无法确定企业");
//        }

        if(StringUtil.isBlank(supplierSignUp.getSellerCompanyId())){
            return Message.fail("无法确定企业");
        }

        int flag = 0;
        if (StrUtil.isNotBlank(supplierSignUp.getBaseId())){
            flag = 1;
        }
        supplierSignUp.setCreator(userId);
        supplierSignUpService.saveOrUpdate(supplierSignUp);
        List<CorporateStrengthPic> corporateStrength = supplierSignUp.getCorporateStrength();
        if (corporateStrength != null && corporateStrength.size() > 0) {
            List<CorporateStrengthPic> corporateStrengthPicList = corporateStrength.stream().peek(i -> {
                i.setId(supplierSignUp.getBaseId());
                i.setType("2-" + supplierSignUp.getType());
            }).collect(Collectors.toList());
            corporateStrengthPicService.saveBatch(corporateStrengthPicList);
        }
        List<ShowSupplierSignUpFile> fileList = supplierSignUp.getFileList();
        if(fileList != null && !fileList.isEmpty()){
            showSupplierSignUpFileService.remove(new QueryWrapper<ShowSupplierSignUpFile>().eq("pk_id",supplierSignUp.getBaseId()));
            List<ShowSupplierSignUpFile> supplierSignUpFileList = fileList.stream().peek(i -> i.setPkId(supplierSignUp.getBaseId())).collect(Collectors.toList());
            showSupplierSignUpFileService.saveBatch(supplierSignUpFileList);
        }
        if (flag == 0) {
//            SignUpMessage message = new SignUpMessage();
//            message.setSignUpUserId(supplierSignUp.getCreator());
//
//            String enterpriseName = enterpriseHistoryService.queryEnterpriseName(supplierSignUp.getCreator());
//            message.setEnterpriseName(enterpriseName);
//
//            message.setSupplierInquiryOrderId(supplierSignUp.getOrderId());
//            message.setSignUpId(supplierSignUp.getBaseId());
//
//            LambdaQueryWrapper<LuLianSupplierInquiryOrder> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(LuLianSupplierInquiryOrder::getBaseId, supplierSignUp.getOrderId());
//            LuLianSupplierInquiryOrder supplierInquiryOrder = supplierInquiryOrderService.getOne(wrapper);
//            message.setSupplierInquiryOrderUserId(supplierInquiryOrder.getCreator());
//            message.setSupplierInquiryOrderName(supplierInquiryOrder.getBaseName());
//
//            boolean res = signUpMessageService.save(message);
//            if (! res) {
//                return Message.fail("报名消息创建失败");
//            }

        }
        if(StringUtil.isNotBlank(supplierSignUp.getMaiJiaUserId())){
            notificationUtils.saveAndSendMessage(userId, supplierSignUp.getMaiJiaUserId(), supplierSignUp.getBaoJiaFangEnterpriseName() + StrUtil.COMMA + NotificationConstant.NOTIFICATION_TYPE_SUPPLIER_SIGNUP);
        }
        return Message.success();
    }

    /**
     * 查询报名消息
     * @date 2024/08/07
     * @author WongMz
     */
    @GetMapping("/message")
    public Message querySignUpMessage(@RequestParam("userId") String userId) {
        try {
            if (StrUtil.isBlank(userId)) {
                logger.error("查询异常：===》入参异常");
                return Message.fail("入参异常");
            }
            return Message.success(signUpMessageService.querySignUpMessage(userId));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 查询已报名个数
     * @date 2024/08/07
     * @author WongMz
     */
    @GetMapping("/count")
    public Message querySignUpCount(@RequestParam("userId") String userId) {
        try {
            if (StrUtil.isBlank(userId)) {
                logger.error("查询异常：===》入参异常");
                return Message.fail("入参异常");
            }
            LambdaQueryWrapper<LuLianSupplierSignUp> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LuLianSupplierSignUp::getCreator, userId);
            int count = supplierSignUpService.count(wrapper);
            return Message.success(count);
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 查询报报名列表（条件、分页）
     *
     * @param
     * @date 2024/08/30
     * @author WongMz
     */
    @GetMapping("/queryList")
    public Message querySignUpListPage(@RequestParam("pageNum") Integer pageNum,
                                       @RequestParam("pageSize") Integer pageSize,
                                       @RequestParam(value = "orderName", required = false) String orderName) {
        try {
            if (pageNum == null || pageSize == null) {
                logger.error("查询异常：===》入参异常");
                return Message.fail("入参异常");
            }
            String userId = findUserId();
            if (StrUtil.isNotBlank(userId)) {
                Page<LuLianSupplierSignUp> page = startPage(pageNum, pageSize);
                return Message.success(supplierSignUpService.querySignUpListPage(page, userId, orderName));
            } else {
                System.out.println("------------------未登录------------------");
                return Fail("请先注册/登录！");
            }
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }
}